package com.yuyang.wifi;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.mobads.sdk.api.BDAdConfig;
import com.baidu.mobads.sdk.api.BDDialogParams;
import com.baidu.mobads.sdk.api.MobadsPermissionSettings;
import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.fanjun.keeplive.KeepLive;
import com.fanjun.keeplive.config.ForegroundNotification;
import com.fanjun.keeplive.config.ForegroundNotificationClickListener;
import com.fanjun.keeplive.config.KeepLiveService;
import com.google.gson.Gson;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.SdkConfig;
import com.oygo.hunter.KeepLiveWrapper;
import com.oygo.hunter.decode.DecodeWrapper;
import com.oygo.hunter.utils.AccountUtils;
import com.qq.e.comm.managers.GDTADManager;
import com.qq.e.comm.managers.setting.GlobalSetting;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.yuyang.wifi.constant.AdSettingProperties;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.constant.ConstantsMsg;
import com.yuyang.wifi.jobservice.AppService;
import com.yuyang.wifi.jobservice.KeepAliveJobService;
import com.yuyang.wifi.utils.AdSettingHelper;
import com.yuyang.wifi.utils.DeviceInfoUtils;
import com.yuyang.wifi.utils.DoubleProceSPUtils;
import com.yuyang.wifi.utils.FileScreenUtil;
import com.yuyang.wifi.utils.PreferencesProviderUtils;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.TTAdManagerHolder;
import com.yuyang.wifi.utils.eventbus.BaseEventManager;

import net.idik.lib.cipher.so.CipherClient;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ProcessLifecycleOwner;
import cn.jpush.android.api.JPushInterface;
import okhttp3.internal.platform.Reflection;


public class MyApplication extends Application {


    private static MyApplication instance = null;
    public static MyApplication myApplication;
    public static String saveBmd;
    public static int mCount;
    public static int stealPs;
    private String TAG = "bugly";
    private static HashMap<String, String> eventIdMap;
    private static HashMap<String, String> channelIdMap;
    private static HashMap<String, String> csjAllMap;
    private static HashMap<String, String> ylhAllMap;
    private UMShareAPI umShareAPI;
    private static final String APP_KEY = "831899f8-567c-4e75-8922-7f345bb57f7c";
    private static final String APP_WB_KEY = "cK7PgwbAr";

    static {
        System.loadLibrary("cql-ref");
    }

//    {
//        PlatformConfig.setWeixin("wxd2688f1a748eeacc", "ba82e181b7920ffece8769ca86564c7a");
//        PlatformConfig.setQQZone("101542597", "5f9f8833f43102b8a9d0b0e32153b38e");
////        PlatformConfig.setSinaWeibo("1302093393", "327d779f723a583fdeffd7fe4e29b2da");
////        PlatformConfig.setQQZone("1105846495", "H4ea7tzgcvA6jwj1");
//    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        Log.d("cql", "attachBase");
        Reflection.unseal(base);
        DecodeWrapper.key = CipherClient.encryptKey1();
        AccountUtils.init(this);
        KeepLiveWrapper.start(base);
        //定义前台服务的默认样式。即标题、描述和图标
        ForegroundNotification foregroundNotification = new ForegroundNotification("测试", "描述", R.mipmap.ic_launcher,
                //定义前台服务的通知点击事件
                new ForegroundNotificationClickListener() {

                    @Override
                    public void foregroundNotificationClick(Context context, Intent intent) {
                    }
                });
        //启动保活服务
        KeepLive.startWork(this, KeepLive.RunMode.ROGUE, foregroundNotification,
                //你需要保活的服务，如socket连接、定时任务等，建议不用匿名内部类的方式在这里写
                new KeepLiveService() {
                    /**
                     * 运行中
                     * 由于服务可能会多次自动启动，该方法可能重复调用
                     */
                    @Override
                    public void onWorking() {

                    }

                    /**
                     * 服务终止
                     * 由于服务可能会被多次终止，该方法可能重复调用，需同onWorking配套使用，如注册和注销broadcast
                     */
                    @Override
                    public void onStop() {

                    }
                }
        );

    }

    @Override
    public void onCreate() {
        super.onCreate();
        FileScreenUtil.createDirectory();
        Log.d("cql", "onCreate");
//        Reflection.unseal(this);
//        PowerGem.initParam("com.yuyang.wifi", "clean", "assist", "other");
//        PowerGem.getInstance().startWork(this.getApplicationContext());
//        if (PowerGem.getInstance().isGemProcess()) {
//            return;
//        }
//        com.venus.keepalive.e.a(this, NewMainHomeActivity.class);
        Log.e("MyApplication===", "就疯狂的世界风口浪尖上了");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            PreferencesProviderUtils.putString(this, "hhhh", AppConstant.KEY_IS_PLAYING_AD, "");
            startForegroundService(new Intent(this, AppService.class));
        } else {
            startService(new Intent(this, AppService.class));
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            KeepAliveJobService.startJob(this);
        }
        initYlhAppChannel();
        initApplication();
        initFresco();
        initChannelConfig();
        //initLeak();
        //穿山甲SDK初始化
        //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现content为null的异常
        TTAdManagerHolder.init(this);
        // initAd();//穿山甲初始化
        initYlh();//优量汇
        initJPush();//极光推送初始化
        initBaiDu();
        initUmeng();
        initUmengShare();
        SpUtil.init(PreferenceManager.getDefaultSharedPreferences(this));
        DoubleProceSPUtils.init(this, "sssss");
        EventBus.builder().throwSubscriberException(true).installDefaultEventBus();
        //Logger初始化。
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new MyLifecycleObserver());
    }

    private void initBaiDu() {
        if (getProcessName(this).startsWith("com.baidu.mobads.demo.main")) {
            // 初始化信息，初始化一次即可，（此处用startsWith()，可包括激励/全屏视频的进程）
            // https、视频缓存空间有特殊需求可动态配置，一般取默认值即可，无需设置
            BDAdConfig bdAdConfig = new BDAdConfig.Builder()
                    // 1、设置app名称，可选
                    .setAppName("随身WiFi")
                    // 2、应用在mssp平台申请到的appsid，和包名一一对应，此处设置等同于在AndroidManifest.xml里面设置
                    .setAppsid("f5b4a0f2")
                    // 3、设置下载弹窗的类型和按钮动效样式，可选
                    .setDialogParams(new BDDialogParams.Builder()
                            .setDlDialogType(BDDialogParams.TYPE_BOTTOM_POPUP)
                            .setDlDialogAnimStyle(BDDialogParams.ANIM_STYLE_NONE)
                            .build())
                    .build(this);
            bdAdConfig.init();

            // 设置SDK可以使用的权限，包含：设备信息、定位、存储、APP LIST
            // 注意：建议授权SDK读取设备信息，SDK会在应用获得系统权限后自行获取IMEI等设备信息
            // 授权SDK获取设备信息会有助于提升ECPM
            //设置SDK获取设备信息权限（建议）
            MobadsPermissionSettings.setPermissionReadDeviceID(AdSettingHelper.getInstance()
                    .getBooleanFromSetting(AdSettingProperties.COMMON_PERMISSION_PHONE_STATE, true));
            //设置SDK获取应用列表权限（建议）
            MobadsPermissionSettings.setPermissionAppList(AdSettingHelper.getInstance()
                    .getBooleanFromSetting(AdSettingProperties.COMMON_PERMISSION_APP_LIST, true));
            //设置SDK获取粗略定位权限
            MobadsPermissionSettings.setPermissionLocation(AdSettingHelper.getInstance()
                    .getBooleanFromSetting(AdSettingProperties.COMMON_PERMISSION_LOCATION, false));
            //设置SDK获取外部存储权限
            MobadsPermissionSettings.setPermissionStorage(AdSettingHelper.getInstance()
                    .getBooleanFromSetting(AdSettingProperties.COMMON_PERMISSION_STORAGE, false));
        }
    }

    public void initSDK(Context appContext) {
        try {
            KsAdSDK.init(appContext, new SdkConfig.Builder()
                    .appId(ConstantsMsg.KS_APP_ID) // 测试aapId，请联系快手平台申请正式AppId，必填
                    .appName("随身WiFi") // 测试appName，请填写您应用的名称，非必填
                    .appKey(APP_KEY) // 直播sdk安全验证，接入直播模块必填
                    .appWebKey(APP_WB_KEY) // 直播sdk安全验证，接入直播模块必填
                    // Feed和入口组件，夜间模式样式配置，如果不配置 默认是"ks_adsdk_night_styles.xml"
                    .nightThemeStyleAssetsFileName("ks_adsdk_night_styles.xml")
                    .showNotification(true) // 是否展示下载通知栏
                    .debug(true)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initChannelConfig() {

        Gson gson = new Gson();
        // 初始化hash表
        // 穿山记
        // 1.激励视频
        String csjJiLiJson = getJson("CsjAllConfig.json", this);
        csjAllMap = new HashMap<>();
        csjAllMap = gson.fromJson(csjJiLiJson, csjAllMap.getClass());

        //优量汇
        //1.激励视频
        String ylhJiLiJson = getJson("YlhAllConfig.json", this);
        ylhAllMap = new HashMap<>();
        ylhAllMap = gson.fromJson(ylhJiLiJson, ylhAllMap.getClass());
    }


    private void initYlhAppChannel() {
        // 初始化hash表
        String json = getJson("ULHChannelMap.json", this);
        Gson gson = new Gson();
        channelIdMap = new HashMap<>();
        channelIdMap = gson.fromJson(json, channelIdMap.getClass());
    }


    private void initYlh() {
        GDTADManager.getInstance().initWith(this, ConstantsMsg.YLH_APP_ID);
        String channelName = DeviceInfoUtils.getUmChannelName(this);
        if (!TextUtils.isEmpty(channelName) && channelIdMap.size() != 0) {
            String channelId = channelIdMap.get(channelName);
            if (!TextUtils.isEmpty(channelId)) {
                Log.e("sssssssssss", "channelId===: " + channelId);
                GlobalSetting.setChannel(Integer.valueOf(channelId));
            } else {
                GlobalSetting.setChannel(999);
            }
        } else {
            GlobalSetting.setChannel(999);
        }
        GlobalSetting.setEnableMediationTool(true);
    }

//    private void initLeak() {
//        if (LeakCanary.isInAnalyzerProcess(this)) {
//            // This process is dedicated to LeakCanary for heap analysis.
//            // You should not init your app in this process.
//            return;
//        }
//        LeakCanary.install(this);
//    }

    private void initAd() {
        //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现content为null的异常
        TTAdSdk.init(this,
                new TTAdConfig.Builder()
                        .appId(ConstantsMsg.CSJ_APP_ID)
                        .useTextureView(false) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
                        .appName("随身WiFi")
                        .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_NO_TITLE_BAR)
                        .allowShowNotify(true) //是否允许sdk展示通知栏提示
                        .allowShowPageWhenScreenLock(true) //是否在锁屏场景支持展示广告落地页
                        .debug(true) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
                        .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI, TTAdConstant.NETWORK_STATE_3G, TTAdConstant.NETWORK_STATE_2G, TTAdConstant.NETWORK_STATE_4G) //允许直接下载的网络状态集合
                        .supportMultiProcess(false) //是否支持多进程，true支持
                        .build());


        //如果明确某个进程不会使用到广告SDK，可以只针对特定进程初始化广告SDK的content
        //if (PROCESS_NAME_XXXX.equals(processName)) {
        //   TTAdSdk.init(context, config);
        //}
    }

    private void initUmengShare() {
//        UMConfigure.init(this, "5f508833636b2b13182bec89"
//                , "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
        PlatformConfig.setWeixin("wx812ee8bebfc73410", "06c3d3b1edf240f3c3c4e477a4ddc2a9");
        umShareAPI = UMShareAPI.get(this);
    }

    private void initJPush() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

    //5f4deda412981d3ca30c6390
    private void initUmeng() {
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_DUM_NORMAL);
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, null);
        UMConfigure.setLogEnabled(false);// 打开统计SDK调试模式
        MobclickAgent.setCatchUncaughtExceptions(false);// isEnable: false-关闭错误统计功能；true-打开错误统计功能（默认打开）
        // 初始化hash表
        String json = getJson("PBUMSocialEventMap.json", this);
        Gson gson = new Gson();
        eventIdMap = new HashMap<>();
        eventIdMap = gson.fromJson(json, eventIdMap.getClass());

    }

    private void initFresco() {
        Fresco.initialize(this);
    }

    public static Context getApp() {
        return myApplication;
    }


    private void initApplication() {
        if (null == instance) {
            instance = this;
        }
    }

    public static MyApplication getInstance() {
        return instance;
    }

    public UMShareAPI getUmShareAPI() {
        return umShareAPI;
    }

    public static void logEvent(@NonNull Context context, @NonNull String eventName) {
        String eventId = eventIdMap.get(eventName);
        if (!TextUtils.isEmpty(eventId)) {
            MobclickAgent.onEvent(context, eventId);
        }
    }

    public static void logEvent(@NonNull Context context, @NonNull String eventName, @Nullable HashMap params) {
        String eventId = eventIdMap.get(eventName);
        if (null != eventId) {
            MobclickAgent.onEvent(context, eventId, params);
        }
    }

    public static String getCsjAdIdChannel(@NonNull String channelId) {
        String adId = csjAllMap.get(channelId);
        if (!TextUtils.isEmpty(adId)) {
            return adId;
        }
        return "";
    }

    public static String getYlhChannel(@NonNull String channelId) {
        String adId = ylhAllMap.get(channelId);
        if (!TextUtils.isEmpty(adId)) {
            return adId;
        }
        return "";
    }

    public static String getJson(String fileName, Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public class MyLifecycleObserver implements LifecycleObserver {

        //App处于前台可见状态。

        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        public void create() {
            Log.e("MyApplication===", "create");
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void start() {

        }

        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        public void resume() {
            PreferencesProviderUtils.putString(MyApplication.getInstance(), "hhhh", AppConstant.KEY_IS_PLAYING_AD, "play");
            Log.e("MyApplication===", "内部");
            Log.e("url===", "我是" + "内部");
        }

        //此后App进入不可见状态/后台

        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        public void pause() {

        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void stop() {
            BaseEventManager.post(null, "yes");//发送eventbus消息通知
            PreferencesProviderUtils.putString(MyApplication.getInstance(), "hhhh", AppConstant.KEY_IS_PLAYING_AD, "");
            Log.e("MyApplication===", "外部");
            Log.e("url===", "我是" + "外部");
        }
    }

    private String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }


}
